export const jsUtils = {}
/**
 * 去抖动
 * @param fn
 * @param delay
 * @returns {Function}
 */
jsUtils.debounce = function (fn, delay) {
  let context = this,
    timer = null;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);

      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    } else {
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    }
  }
}

/**
 * 节流
 * @param fn
 * @param delay
 * @returns {Function}
 */
jsUtils.throttle = function (fn, delay) {
  let context = this,
    timer = null,
    remaining = 0,
    previous = new Date();

  return function () {
    let args = arguments;
    let now = new Date();
    remaining = now - previous;
    if (remaining >= delay) {
      if (timer) {
        clearTimeout(timer);
      }

      fn.apply(context, args);
      previous = now;
    } else {
      if (!timer) {
        timer = setTimeout(function () {
          fn.apply(context, args);
          previous = new Date();
        }, delay - remaining);
      }
    }
  };
}
/**
 * 去除前后空格
 * @private
 * @param str
 * @returns {string}
 */
jsUtils.trim = function(str) {
  return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
